import {
  Injectable,
  NestMiddleware,
  Param,
  Get,
  Query,
  Req,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { defaultConfig } from '@game/config/config';
import { ReqUtils } from '@common/utils/req.utils';
@Injectable()
export class ReqMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    //通过获取外部配置文件的方式解决硬编码问题
    const appkey = defaultConfig.aeskey;
    console.log(appkey + '获取1');
    const query: any = req.query;

    let data = {};
    if (req.method.toUpperCase() == 'GET') {
      // timestamp token，ip，页面路由名
      data = req.query;
      //非开发环境 且是app平台标识
      if (defaultConfig.NODE_ENV != 'dev' || query?.platform == 'web') {
        if (!ReqUtils.signParams(data)) {
          throw new HttpException('非法请求', HttpStatus.INTERNAL_SERVER_ERROR);
        }
      }
    } else if (req.method.toUpperCase() == 'POST') {
      // 校验
      if (defaultConfig.NODE_ENV != 'dev' || query?.platform == 'web') {
        data = req.body.data;

        data = await ReqUtils.decryptUserInfoData(data);

        if (!ReqUtils.signParams(data)) {
          throw new HttpException('非法请求', HttpStatus.INTERNAL_SERVER_ERROR);
        }
        // 把数据重新写到post里面
        Object.keys(data).map((key) => {
          req.body[key] = data[key];
        });
        if (data['data']) {
          Object.keys(data['data']).map((key) => {
            req.body[key] = data['data'][key];
          });
        }

        delete req.body['data'];

        console.log('data:', req.body, query?.platform);
      }
    }

    next(); // 签名验证通过，继续处理请求
  }
}
